<template>
    <div class="search-suggestion">
        <van-cell v-for="(item, index) in suggestions" :key="index" center @click="$emit('search', item)">
            <template #icon>
                <van-icon name="search" />
            </template>
            <template #title>
                <span class="custom-title" v-html="highlight(item)"></span>
            </template>
        </van-cell>
    </div>
</template>

<script>
import { getSearchSuggestions } from '../../../api/search'
import { debounce } from 'lodash'
export default {
    name: 'SearchSuggestion',
    props: {
        searchText: {
            type: String,
            required: true
        }
    },
    data() {
        return {
            suggestions: [],
        }
    },
    watch: {
        searchText: {
            immediate: true,
            handler: debounce(function (newValue) {
                this.loadSearchSuggestions(newValue)
            }, 400)
        }
    },
    methods: {
        async loadSearchSuggestions(value) {
            const { data } = await getSearchSuggestions(value)
            this.suggestions = data.data.options
            if (!this.suggestions[0]) {
                this.suggestions = []
            }
        },
        highlight(text) {
            const highlight = `<span class="active">${this.searchText}</span>`
            const reg = new RegExp(this.searchText, 'g')
            return text.replace(reg, highlight)
        }
    }
}
</script>

<style scoped lang="less">
.search-suggestion {
    :deep(span.active) {
        color: red;
    }
}
</style>